package com.net.okhttphelper.download;

import android.os.Handler;
import android.os.Looper;

import java.io.IOException;

import androidx.annotation.NonNull;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;

/**
 * 监听下载进度
 * @author jie
 */
public class ProgressResponseBody extends ResponseBody{

    private final ResponseBody responseBody;
    private final DownloadListener downloadListener;
    private BufferedSource bufferedSource;
    /**
     * 主线程handler
     */
    private final Handler mHandler = new Handler(Looper.getMainLooper());

    public ProgressResponseBody(ResponseBody responseBody, DownloadListener downloadListener){
        this.responseBody = responseBody;
        this.downloadListener = downloadListener;
    }

    @Override
    public MediaType contentType() {
        return responseBody.contentType();
    }

    @Override
    public long contentLength() {
        return responseBody.contentLength();
    }

    @NonNull
    @Override
    public BufferedSource source() {
        if (bufferedSource == null){
            bufferedSource = Okio.buffer(source(responseBody.source()));
        }
        return bufferedSource;
    }

    private Source source(Source source){
        return new ForwardingSource(source) {
            long totalBytesRead = 0L;
            long contentLength = 0L;
            @Override
            public long read(@NonNull Buffer sink, long byteCount) throws IOException {
                long bytesRead = super.read(sink, byteCount);
                //增加当前读取的字节数，如果读取完成了bytesRead会返回-1
                totalBytesRead += bytesRead != -1 ? bytesRead : 0;
                if (contentLength == 0){
                    contentLength = contentLength();
                }
                //回调，如果contentLength()不知道长度，会返回-1
                if (downloadListener != null){
//                    int progress = ((int) (totalBytesRead * 1.0f / contentLength * 100));
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            downloadListener.progress(totalBytesRead, contentLength);
                        }
                    });
                }
                return bytesRead;
            }
        };
    }
}
